const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('electronAPI', {
  getVersion: () => ipcRenderer.invoke('app:get-version'),
  
  dialog: {
    openFile: (options) => ipcRenderer.invoke('dialog:open-file', options),
    saveFile: (options) => ipcRenderer.invoke('dialog:save-file', options)
  },

  httpClient: {
    request: (config) => ipcRenderer.invoke('module:http-client:request', config)
  },

  httpServer: {
    start: (config) => ipcRenderer.invoke('module:http-server:start', config),
    stop: () => ipcRenderer.invoke('module:http-server:stop'),
    addRoute: (route, handler) => ipcRenderer.invoke('module:http-server:add-route', route, handler),
    onRequestLog: (callback) => {
      ipcRenderer.on('http-server:request-log', (event, data) => callback(data))
    }
  },

  mqtt: {
    connect: (config) => ipcRenderer.invoke('module:mqtt:connect', config),
    subscribe: (topic, qos) => ipcRenderer.invoke('module:mqtt:subscribe', topic, qos),
    publish: (topic, message, qos, retain) => ipcRenderer.invoke('module:mqtt:publish', topic, message, qos, retain),
    disconnect: () => ipcRenderer.invoke('module:mqtt:disconnect'),
    onConnected: (callback) => {
      ipcRenderer.on('mqtt:connected', callback)
    },
    onMessage: (callback) => {
      ipcRenderer.on('mqtt:message', (event, data) => callback(data))
    },
    onError: (callback) => {
      ipcRenderer.on('mqtt:error', (event, error) => callback(error))
    },
    onDisconnected: (callback) => {
      ipcRenderer.on('mqtt:disconnected', callback)
    }
  },

  menu: {
    onNewConnection: (callback) => {
      ipcRenderer.on('menu-new-connection', callback)
    },
    onImportConfig: (callback) => {
      ipcRenderer.on('menu-import-config', callback)
    },
    onExportConfig: (callback) => {
      ipcRenderer.on('menu-export-config', callback)
    },
    onOpenModule: (callback) => {
      ipcRenderer.on('menu-open-module', (event, module) => callback(module))
    },
    onOpenSettings: (callback) => {
      ipcRenderer.on('menu-open-settings', (event, section) => callback(section))
    }
  },

  removeAllListeners: (channel) => {
    ipcRenderer.removeAllListeners(channel)
  }
})